package com.tanhua.server.service;

import com.aliyun.oss.internal.OSSUtils;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 图片上传到阿里云并进行人脸识别
     * @param headPhoto
     * @param userId
     * @throws IOException
     */
    public void updateHead(MultipartFile headPhoto, Long userId) throws IOException {
        //1、将图片上传到阿里云oss
        String imgUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imgUrl);
        if (!detect){
            //不包含人脸，删除照片
            String replace = imgUrl.replace("https://yinfeilong.oss-cn-hangzhou.aliyuncs.com/", "");
            ossTemplate.delete(replace);
            throw new BusinessException(ErrorResult.faceError());
        }else{
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userId);
            userInfo.setAvatar(imgUrl);
            userInfoApi.update(userInfo);
        }


    }

    /**
     * 根据id查询userinfo信息封装到vo中
     * @param userID
     * @return
     */
    public UserInfoVo getById(Long userID) {
        UserInfoVo userInfoVo = new UserInfoVo();

        UserInfo userInfo = userInfoApi.getById(userID);
        BeanUtils.copyProperties(userInfo,userInfoVo);

        if(userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }

        return userInfoVo;
    }

    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }
}
